<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <style>
        *{
            margin:0px;
            padding:0px;
        }
    </style>
</head>

<body>
<div style="margin-left:400px">
    <h3><div id="title">123</div></h3>
    <div style="border:1px solid;width: 600px;height: 500px;">
        <div id="msgArea" style="width:100%;height: 100%;text-align:start;resize: none;font-family: 微软雅黑;font-size: 20px;overflow-y: scroll"></div>
    </div>
    <div style="border:1px solid;width: 600px;height: 200px;">
        <div style="width:100%;height: 100%;">
            <textarea id="userMsg" style="width:100%;height: 100%;text-align:start;resize: none;font-family: 微软雅黑;font-size: 20px;"></textarea>
        </div>
    </div>
    <div style="border:1px solid;width: 600px;height: 25px;">
        <button style="float: right;" onclick="sendMsg()">发送</button>
    </div>
</div>
</body>

</html>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script>
    var ws;
    $(function(){
        link();
    })

    function link () {
        ws = new WebSocket("ws://106.12.201.205:9501");//连接服务器
        ws.onopen = function(event){
            //console.log(event);
            alert('连接了');
        };
        ws.onmessage = function (event) {
            //console.log(event.data);return;
            var data = JSON.parse(event.data);
            console.log(data);
            if (data['type'] == 3) {
                return;
            }
            localStorage.setItem('ws_id', data['userFd']);
            localStorage.setItem('ws_to_id', data['toUserFd']);
            var userInfo = '我是' + data['userFd'] + '号（会员），';
            if (data['toUserFd']) {
                userInfo += '我在和' + data['toUserFd'] + '号聊天';
            } else {
                userInfo += '我没有和任何人聊天';
            }
            $("#title").text(userInfo);
            if (data['type'] == 1) {
                sendIdentity();
                return;
            }
            var msg = "<p>"+data['msg']+"</p>";
            $("#msgArea").append(msg);
            var scrollTop = $("#msgArea")[0].scrollHeight;
            $("#msgArea").scrollTop(scrollTop);
        }
        ws.onclose = function(event){alert("已经与服务器断开连接\r\n当前连接状态："+this.readyState);};

        ws.onerror = function(event){alert("WebSocket异常！");};
    }

    function sendMsg(){
        var msg = $("#userMsg").val();
        var data = {type:2,userFd:localStorage.getItem('ws_id'),toUserFd:localStorage.getItem('ws_to_id'),msg:msg};
        $("#userMsg").val('');
        ws.send(JSON.stringify(data));
    }

    function sendIdentity() {
        var data = {type:3,userFd:localStorage.getItem('ws_id'),identity_type:2,toUserFd:localStorage.getItem('ws_to_id')};
        ws.send(JSON.stringify(data));
    }
</script>
